/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, NetInfo, Alert, PermissionsAndroid} from 'react-native';
// import { NetworkInfo } from 'react-native-network-info';
// import WifiManager from 'react-native-wifi';
// import SystemSetting from 'react-native-system-setting'
// import wifi from 'react-native-wifi-checker';

import wifi from 'react-native-android-wifi';

// const IOSWifiManager = NativeModules.IOSWifiManager

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});



type Props = {};
export default class App extends Component<Props> {

  constructor(props) {
    super(props);
    this.state = {
      ssid: '',
      bssid: '',
      ssidArray: []
    }
  }

  componentDidMount() {

    // wifi.getWifiList()
    // .then((wifiList) => {
    //   // do something with the list for example
    //   console.log(wifiList);
    // }).done();

    // Get Local IP
    // NetworkInfo.getIPAddress(ip => {
    //   console.log(ip);
    // });
    
    // // Get IPv4 IP
    // NetworkInfo.getIPV4Address(ipv4 => {
    //   console.log(ipv4);
    // });
    
    // // Get Broadcast
    // NetworkInfo.getBroadcast(address => {
    //   console.log(address);
    // });
    
    // // Get SSID
    // NetworkInfo.getSSID(ssid => {
    //   console.log(ssid);
    //   this.setState({
    //     ssid: ssid
    //   })
    // });
    
    // // Get BSSID
    // NetworkInfo.getBSSID(ssid => {
    //   console.log(ssid);
    //   this.setState({
    //     bssid: ssid
    //   })
    // });
    let _this = this;
    NetInfo.getConnectionInfo().then((connectionInfo) => {
      console.log(connectionInfo);
      _this.setState({
        bssid: connectionInfo.type
      })
    });

    // SystemSetting.isWifiEnabled().then((enable)=>{
    //     const state = enable ? 'On' : 'Off';
    //     console.log('Current wifi is ' + state);
    //     Alert.alert(
    //       'Alert Title',
    //       state,
    //       [
    //         {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
    //         {text: 'OK', onPress: () => console.log('OK Pressed')},
    //       ],
    //       { cancelable: false }
    //     )
    // })
    
    // SystemSetting.switchWifi(()=>{
    //   console.log('switch wifi successfully');
    //   Alert.alert(
    //     'Alert Title',
    //     "switch wifi successfully",
    //     [
    //       {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
    //       {text: 'OK', onPress: () => console.log('OK Pressed')},
    //     ],
    //     { cancelable: false }
    //   )
    // }, () => {
    //   console.log('234567');
    // })

    async function requestCameraPermission() {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
          {
            'title': 'Wifi networks',
            'message': 'We need your permission in order to find wifi networks'
          }
        )
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log("Thank you for your permission! :)")
        } else {
          console.log("You will not able to retrieve wifi available networks list")
        }
      } catch (err) {
        console.warn(err)
      }
    }

    requestCameraPermission();

    wifi.isEnabled((isEnabled) => {
      if (isEnabled) {
        console.log("wifi service enabled");
      } else {
        console.log("wifi service is disabled");
      }
    });

    wifi.getSSID((ssid) => {
      console.log(ssid);
    });

    wifi.getBSSID((bssid) => {
      console.log(bssid);
    });

    wifi.loadWifiList((wifiStringList) => {
      var wifiArray = JSON.parse(wifiStringList);
        console.log(wifiArray);
        this.setState({
          ssidArray: wifiArray
        })
        // wifi.disconnect();
        // wifi.findAndConnect('Frog2.4GHz', 'FrogsHealth@1', (found) => {
        //   if (found) {
        //     console.log("wifi is in range");
        //   } else {
        //     console.log("wifi is not in range");
        //   }
        // });
      },
      (error) => {
        console.log(error);
      }
    );

    wifi.connectionStatus((isConnected) => {
      if (isConnected) {
          console.log("is connected");
        } else {
          console.log("is not connected");
      }
    });

    

    // WifiManager.connectToProtectedSSID(ssid, password, isWep)
    // .then(() => {
    //     console.log('Connected successfully!')
    // }, () => {
    //     console.log('Connection failed!')
    // })
    
    // WifiManager.getCurrentWifiSSID()
    // .then((ssid) => {
    //   Alert.alert(
    //     'Alert Title',
    //     "Your current connected wifi SSID is " + ssid,
    //     [
    //       {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
    //       {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
    //       {text: 'OK', onPress: () => console.log('OK Pressed')},
    //     ],
    //     { cancelable: false }
    //   )
    //   console.log("Your current connected wifi SSID is " + ssid)
    // }, () => {
    //   // _this.setState({
    //   //   ssid: ssid
    //   // })
    //   Alert.alert(
    //     'Alert Title',
    //     'Cannot get current SSID!',
    //     [
    //       {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
    //       {text: 'OK', onPress: () => console.log('OK Pressed')},
    //     ],
    //     { cancelable: false }
    //   )
    //   console.log('Cannot get current SSID!')
    // })
  }

  

  render() {
    
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>{this.state.bssid}</Text>
        {
          this.state.ssidArray.map ((item, index) => {
            return (
              <Text style={styles.instructions}>{item.SSID}</Text>
            )
          })
        }
        <Text style={styles.instructions}>{instructions}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
